/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.codec.text;

import java.nio.charset.Charset;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cqcis.uip.base.framework.FrameworkConstants;
import com.cqcis.uip.base.framework.codec.ObjectEncoder;
import com.cqcis.uip.base.framework.common.ControlMsg;
import com.cqcis.uip.base.framework.common.TelnetCommand;
import com.cqcis.uip.base.framework.utils.ByteBuffer;

/**
 * telnet协议编码器实现
 * 
 * @author huangmy
 * @date   2008-8-9
 */
public class TextProtocolEncoder implements ObjectEncoder {
	private static Log log = LogFactory.getLog(TextProtocolEncoder.class);
	private Charset charset = Charset.forName("GBK"); // 默认用GBK, 同时兼容英文、简体、繁体
	private boolean printLog = true;
	
	public ByteBuffer encode(Object message) throws Exception {		
		if (message instanceof ControlMsg) {// 应答命令
			ControlMsg cMsg = (ControlMsg)message;
			if (cMsg.getAttribute(FrameworkConstants.TELNETFIRSTSEND_03) != null) {
				// 无效				
				return null;
			}
			
			TelnetCommand cmd = (TelnetCommand)cMsg.getAttachement();
			if (log.isDebugEnabled() && printLog) {
			    log.debug("发送选项协商控制命令: " + cmd);
			}
			
			if (cmd == null) {
				ByteBuffer b = ByteBuffer.allocate(8);
				b.setAutoExpand(true);
				Collection<Object> objects = cMsg.getAttributes().values();
				if (objects != null) {
					for (Object o : objects) {
						if (o instanceof byte[]) {
							b.put((byte[])o);
						} else if (o instanceof Byte) {
							b.put((Byte)o);
						} else if (o instanceof ByteBuffer) {
							b.put((ByteBuffer)b);
						} else {
							b.putString(o.toString(), this.charset.newEncoder());
						}
					}
				}
				
				return b.flip();
			}
			
			return cmd.toByteBuffer();
		}
		
		String s = message.toString();
		
		if (log.isDebugEnabled() && printLog) {
			log.debug("发送命令数据: " + s);
		}
				
		ByteBuffer buffer = ByteBuffer.allocate(s.length()).setAutoExpand(true);
		buffer.putString(s, this.charset.newEncoder());		
		buffer.flip();
		return buffer;
	}

	public void setCharset(String charset) {
		this.charset = Charset.forName(charset);
	}
	
	public void setPrintLog(boolean printLog) {
		this.printLog = printLog;
	}
}
